'use client';

import { useEffect, useRef } from 'react';
import styled from 'styled-components';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import {
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  GridComponent,
  GraphicComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  PieChart,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  GridComponent,
  GraphicComponent,
  CanvasRenderer
]);

// 样式组件
const StatusContainer = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  padding-bottom: 10px;
`;

const ChartContainer = styled.div`
  flex: 1;
  width: 100%;
  margin-bottom: 20px;
`;

const StatusInfo = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  padding: 10px;
  background: rgba(24, 144, 255, 0.1);
  border-radius: 4px;
  border-left: 3px solid #1890ff;
`;

const StatusItem = styled.div`
  display: flex;
  align-items: center;
  margin: 0 5px;
`;

const StatusIndicator = styled.div<{ color: string }>`
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: ${props => props.color};
  margin-right: 8px;
  box-shadow: 0 0 5px ${props => props.color};
`;

const StatusLabel = styled.span`
  font-size: 12px;
  color: #a0cfff;
  margin-right: 5px;
`;

const StatusValue = styled.span`
  font-size: 16px;
  font-weight: bold;
  color: white;
  text-shadow: 0 0 5px rgba(255, 255, 255, 0.3);
`;

// Tooltip参数类型
interface TooltipParams {
  name: string;
  value: number;
  percent: number;
}

// 模拟设备状态数据
const deviceStatusData = [
  { 
    value: 42, 
    name: '在线', 
    itemStyle: { 
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#7be141' },
        { offset: 1, color: '#52c41a' }
      ])
    }
  },
  { 
    value: 8, 
    name: '离线', 
    itemStyle: { 
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#a6a6a6' },
        { offset: 1, color: '#8c8c8c' }
      ])
    }
  },
  { 
    value: 3, 
    name: '警告', 
    itemStyle: { 
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#ffcb47' },
        { offset: 1, color: '#faad14' }
      ])
    }
  },
  { 
    value: 2, 
    name: '报警', 
    itemStyle: { 
      color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: '#ff7875' },
        { offset: 1, color: '#f5222d' }
      ])
    }
  }
];

export default function DeviceStatus() {
  const chartRef = useRef<HTMLDivElement>(null);

  // 初始化图表
  useEffect(() => {
    if (!chartRef.current) return;
    
    const chartInstance = echarts.init(chartRef.current);
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: (params: TooltipParams) => {
          const { name, value, percent } = params;
          return `${name}: ${value} 台 (${percent}%)`;
        },
        backgroundColor: 'rgba(0, 21, 41, 0.8)',
        borderColor: 'rgba(24, 144, 255, 0.3)',
        textStyle: {
          color: '#ffffff'
        }
      },
      legend: {
        orient: 'vertical',
        right: 0,
        top: 'center',
        itemWidth: 12,
        itemHeight: 12,
        itemGap: 15,
        formatter: (name: string) => {
          const item = deviceStatusData.find(item => item.name === name);
          return `{name|${name}} {value|${item?.value}台}`;
        },
        textStyle: {
          rich: {
            name: {
              width: 40,
              color: '#a0cfff'
            },
            value: {
              color: '#ffffff',
              fontWeight: 'bold'
            }
          }
        },
        data: deviceStatusData.map(item => item.name)
      },
      series: [
        {
          name: '设备状态',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: true,
          emphasis: {
            itemStyle: {
              shadowBlur: 20,
              shadowColor: 'rgba(0, 0, 0, 0.8)'
            }
          },
          data: [
            {
              value: 42,
              name: '在线',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#7be141' },
                  { offset: 1, color: '#52c41a' }
                ]),
                borderRadius: 10,
                borderWidth: 2,
                borderColor: 'rgba(82, 196, 26, 0.3)',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              label: {
                show: true,
                position: 'outside',
                formatter: '{d}%',
                fontSize: 10,
                fontWeight: 'bold',
                color: '#7be141',
                distanceToLabelLine: 5
              },
              labelLine: {
                show: true,
                length: 10,
                length2: 12,
                smooth: true,
                lineStyle: {
                  width: 1,
                  type: 'solid',
                  color: '#7be141'
                }
              }
            },
            {
              value: 8,
              name: '离线',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#a6a6a6' },
                  { offset: 1, color: '#8c8c8c' }
                ]),
                borderRadius: 10,
                borderWidth: 2,
                borderColor: 'rgba(140, 140, 140, 0.3)',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              label: {
                show: true,
                position: 'outside',
                formatter: '{d}%',
                fontSize: 10,
                fontWeight: 'bold',
                color: '#a6a6a6',
                distanceToLabelLine: 5
              },
              labelLine: {
                show: true,
                length: 10,
                length2: 12,
                smooth: true,
                lineStyle: {
                  width: 1,
                  type: 'solid',
                  color: '#a6a6a6'
                }
              }
            },
            {
              value: 3,
              name: '警告',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#ffcb47' },
                  { offset: 1, color: '#faad14' }
                ]),
                borderRadius: 10,
                borderWidth: 2,
                borderColor: 'rgba(250, 173, 20, 0.3)',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              label: {
                show: true,
                position: 'outside',
                formatter: '{d}%',
                fontSize: 10,
                fontWeight: 'bold',
                color: '#ffcb47',
                distanceToLabelLine: 5
              },
              labelLine: {
                show: true,
                length: 10,
                length2: 12,
                smooth: true,
                lineStyle: {
                  width: 1,
                  type: 'solid',
                  color: '#ffcb47'
                }
              }
            },
            {
              value: 2,
              name: '报警',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#ff7875' },
                  { offset: 1, color: '#f5222d' }
                ]),
                borderRadius: 10,
                borderWidth: 2,
                borderColor: 'rgba(245, 34, 45, 0.3)',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              label: {
                show: true,
                position: 'outside',
                formatter: '{d}%',
                fontSize: 10,
                fontWeight: 'bold',
                color: '#ff7875',
                distanceToLabelLine: 5
              },
              labelLine: {
                show: true,
                length: 10,
                length2: 12,
                smooth: true,
                lineStyle: {
                  width: 1,
                  type: 'solid',
                  color: '#ff7875'
                }
              }
            }
          ],
          labelLayout: {
            hideOverlap: true,
            moveOverlap: 'shiftY'
          },
          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function () {
            return Math.random() * 200;
          }
        }
      ]
    };
    
    chartInstance.setOption(option);
    
    // 监听窗口大小改变事件
    const resizeHandler = () => {
      if (chartInstance) {
        chartInstance.resize();
      }
    };
    
    window.addEventListener('resize', resizeHandler);
    
    return () => {
      window.removeEventListener('resize', resizeHandler);
      if (chartInstance) {
        chartInstance.dispose();
      }
    };
  }, []);

  // 计算总设备数和在线设备数
  const totalDevices = deviceStatusData.reduce((acc, cur) => acc + cur.value, 0);
  const onlineDevices = deviceStatusData.find(item => item.name === '在线')?.value || 0;
  const onlineRate = Math.round((onlineDevices / totalDevices) * 100);
  const alarmDevices = deviceStatusData.find(item => item.name === '报警')?.value || 0;

  return (
    <StatusContainer>
      <ChartContainer ref={chartRef} />
      
      <StatusInfo>
        <StatusItem>
          <StatusIndicator color="#52c41a" />
          <StatusLabel>总设备:</StatusLabel>
          <StatusValue>{totalDevices}</StatusValue>
        </StatusItem>
        <StatusItem>
          <StatusIndicator color="#1890ff" />
          <StatusLabel>在线率:</StatusLabel>
          <StatusValue>{onlineRate}%</StatusValue>
        </StatusItem>
        <StatusItem>
          <StatusIndicator color="#f5222d" />
          <StatusLabel>报警数:</StatusLabel>
          <StatusValue>{alarmDevices}</StatusValue>
        </StatusItem>
      </StatusInfo>
    </StatusContainer>
  );
} 